<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small"
             :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资讯标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入要查询的资讯标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="一级分类" prop="cate1Id" label-width="auto">
        <el-select v-model="queryParams.cate1Id"
                   placeholder="请选择一级资讯分类"
                   @change="handleQueryParamsChange"
        >
          <!-- @change="handleQueryParamsChange" 的option值会自动传参 -->
          <el-option label="全部" value="" selected ></el-option>
          <el-option v-for="item1 in noticeCategoryLevel1List"
                     :key="item1.id"
                     :value="item1.id"
                     :label="item1.cateName"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类" prop="cateId" label-width="auto">
        <el-select v-model="queryParams.cateId"
                   placeholder="请选择二级资讯分类"
                   @change="handleQuery"
        >
          <el-option label="全部" value="" selected ></el-option>
          <el-option v-for="item2 in noticeCategoryLevel2List"
                     :key="item2.id"
                     :value="item2.id"
                     :label="item2.cateName"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['health:healthNotice:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['health:healthNotice:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['health:healthNotice:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['health:healthNotice:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="healthNoticeList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="资讯id" align="center" width="80" prop="id"/>
      <el-table-column label="二级资讯分类" align="center" width="100" prop="cateName"/>
      <el-table-column label="标题" align="center"
                       :show-overflow-tooltip="true"
                       min-width="35%" prop="title"/>
      <el-table-column label="资讯摘要" align="center"
                       :show-overflow-tooltip="true"
                       min-width="35%" prop="brief"/>
      <el-table-column label="来源" align="center" min-width="15%" prop="source"/>
      <el-table-column label="封面" align="center" prop="coverImage" width="80">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverImage" :width="48" :height="48"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       width="140"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['health:healthNotice:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['health:healthNotice:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资讯管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资讯分类" prop="cateId">
              <treeselect v-model="form.cateId" :options="healthNoticeCategoryOptions"
                          :normalizer="normalizer"
                          :flat="true"
                          placeholder="请选择资讯分类"/>
            </el-form-item>
            <el-form-item label="来源" prop="source">
              <el-input v-model="form.source" placeholder="请输入来源"/>
            </el-form-item>
            <el-form-item label="资讯摘要" prop="brief">
              <el-input v-model="form.brief"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入资讯的摘要"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面" prop="coverImage">
              <image-upload
                :limit="1"
                v-model="form.coverImage"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">资讯详情信息</el-divider>
        <!-- 富文本编辑器 -->
        <editor v-model="noticeDetailDetail" :min-height="150"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listHealthNotice,
  getHealthNotice,
  delHealthNotice,
  addHealthNotice,
  updateHealthNotice
} from "@/api/health/healthNotice";

import {listHealthNoticeCategory} from "@/api/health/healthNoticeCategory";
// treeselect的组件和css一起引入
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "HealthNotice",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 养老资讯de表格数据
      healthNoticeList: [],
      // 资讯详情数据(这里是字符串，后面封装成对象，放在form中)
      noticeDetailDetail: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        cateId: '',  //根据二级分类查询（有了二级分类，就不再需要一级分类）
        cate1Id: '',  //根据一级分类查询
        title: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 资讯分类树选项
      healthNoticeCategoryOptions: [],
      // 资讯全部分类-列表
      healthNoticeCategoryList: [],
      // 资讯二级分类（与一级关联）列表
      noticeCategoryLevel2List:[]
    };
  },
  computed: {
    // 一级分类的列表
    noticeCategoryLevel1List() {
      return this.healthNoticeCategoryList.filter((item) => {
        return item.cateLevel === 1
      })
    },
  },
  watch: {
    queryParams: {
      handler(val, oldVal) {
          //暂时不用
      },
      deep: true
    }
  },
  created() {
    //先获取分类，再获取列表（注意顺序）
    this.getNoticeCategoryList();
    this.getList();
  },
  mounted() {

  },
  methods: {
    /** 查询资讯管理列表 */
    getList() {
      this.loading = true;
      //查询notice列表
      listHealthNotice(this.queryParams).then(response => {
        const healthNoticeListRows = response.rows;
        //向 healthNoticeListRows  中添加 “分类”
        // console.log(healthNoticeListRows)
        this.healthNoticeList = healthNoticeListRows.map(item => {
          for (const noticeCategory of this.healthNoticeCategoryList) {
            if (item.cateId === noticeCategory.id) {
              item.cateName = noticeCategory.cateName
              break;
            }
          }
          return item;
        })
        console.log(this.healthNoticeList)
        this.total = response.total;
        this.loading = false;
      });
    },
    getNoticeCategoryList() {
      listHealthNoticeCategory().then(resp => {
        this.healthNoticeCategoryList = resp.data;
        // console.log(this.healthNoticeCategoryList )
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cateId: null,
        title: null,
        brief: null,
        source: null,
        coverImage: null,
        createBy: null,
        createTime: null
      };
      this.noticeDetailDetail = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加养老资讯";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids
      getHealthNotice(id).then(response => {
        this.form = response.data;
        this.noticeDetailDetail = response.data.noticeDetail ? response.data.noticeDetail.detail : '';
        this.open = true;
        this.title = "修改养老资讯";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.noticeDetail = {
            detail: this.noticeDetailDetail
          };
          if (this.form.id != null) {
            updateHealthNotice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHealthNotice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【养老资讯】编号为"' + ids + '"的数据项？').then(function () {
        return delHealthNotice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 资讯详情序号 */
    rowNoticeDetailIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('health/healthNotice/export', {
        ...this.queryParams
      }, `healthNotice_${new Date().getTime()}.xlsx`)
    },

    /** 转换资讯分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.cateName,
        children: node.children,
        // 禁用父节点，不让选择，但是子节点可以选择
        isDisabled: node.parentId == 0 || node.isRoot == true
      };
    },
    /** 查询资讯分类下拉树结构 */
    getTreeselect() {
      //获取资讯分类的列表（基础数据）
      listHealthNoticeCategory().then(response => {
        this.healthNoticeCategoryOptions = [];
        const data = {id: 0, cateName: '全部分类', children: [], isRoot: true};
        //生成树中各节点
        data.children = this.handleTree(response.data, "id", "parentId");
        this.healthNoticeCategoryOptions.push(data);
      });
    },
    // 当一级分类改变, 联动生成二级养老资讯的分类【列表】
    handleQueryParamsChange(level1Val) {
      //
      this.queryParams.cateId = ''
      this.noticeCategoryLevel2List =  this.healthNoticeCategoryList.filter((item) => {
        return (item.cateLevel === 2 && item.parentId == level1Val)
      })
      // console.log(this.noticeCategoryLevel2List)
      //重新查询List
      this.handleQuery();

    }
  },
};
</script>
